<?php

namespace app\service;

use app\model\ClueMobile;
use app\model\CluePerson;
use app\model\OrderDeal;
use app\model\OrderDealChargeback;
use app\model\OrderEnterpriseCertificateBusiness;
use app\model\OrderEnterpriseCertificateRegister;
use app\model\OrderEnterpriseCompany;
use app\model\OrderEnterpriseExchange;
use app\model\OrderOtherCertificateBusiness;
use app\model\OrderPersonCertificateRegister;
use app\model\OrderTransactionRecord;
use app\stateData;
use think\facade\Db;
use think\Exception;
use think\facade\Log;

class Order
{
    /**
     * 通过order_company_id查询收付款记录 用于企业证书注册公司证书
     * @param $oid
     * @param $type //1收款  2付款
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTransaction($oid, $certificate_code, $type): array
    {
        //查询收付款库所有延伸证书（order_company_id）id信息
        return (new OrderTransactionRecord())->getOrderTransactionStatus($oid, $certificate_code, $type);
    }

    /**
     * 通过certificate_code查询收付款信息，用于倒证 企业证书办理 证书办理业务
     * @param $cer
     * @param $type
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCerTransaction($cer, $type): array
    {
        //查询收付款库证书编码（certificate_code）信息
        return (new OrderTransactionRecord())->getCerStatusDataModel($cer, $type);
    }


    //判断企业证书注册 表单 是否满足成交条件
    public function determineMeetCondition($data): bool
    {
        $field = [
            'certificate_code',
            'business_id',
            'sale_org',
            'sale_uid',
            'reg_unit',
            'price_unit',
            'certificate_id',
            'certificate_b',
            'social_security',
            'cycle',
            'project',
            'people_num',
            'get_org',
            'get_uid',
            'collection_c_price',
            'nickname',
            'id_card',
            'file_illustrate',
            'file_reg',
            'employ_unit_title',
            'employ_unit_name',
            'employ_unit_mobile',
            'notice_id',
        ];

        // 使用foreach循环遍历数组
        foreach ($data as $key => $val) {
            // 判断数组中每个值是否满足 存在 条件
            if (in_array($key, $field, true)) {
                if (empty($val)) {
                    return false;
                }
            }
        }
        return true;
    }


    //收付款单管理补充内容
    public function addTransactionField($data)
    {
        $exchangeModel = new OrderEnterpriseExchange();
        $companyModel = new OrderEnterpriseCompany();
        $businessModel = new OrderEnterpriseCertificateBusiness();
        $otherModel = new OrderOtherCertificateBusiness();
        $transaModel = new OrderTransactionRecord();
        $personModel = new OrderPersonCertificateRegister();
        $orderDealMode = new OrderDeal();


        $result = [];
        foreach ($data as $index => &$datum) {

            $otherData = $otherModel->getCerDataModel($datum['certificate_code']);
            if (!empty($otherData)) {

                $result = $otherData;

                $datum['typess'] = $result['type']; //特价证书标示
                $datum['person_name'] = $result['person_name'];
                $datum['enterprise_name'] = '';
                $datum['employ_unit_title'] = '';
                $datum['sale_org'] = '';
                $datum['reg_unit'] = '';
                $datum['get_price'] = '';
                $datum['yingfu'] = $result['cost_price'];
                $datum['yishou'] = $transaModel->getOrderStatusIdDateYsModel($datum['id'], $datum['create_date'], $datum['order_company_id'], $datum['certificate_code'], 1, 1)['all_price'];
                $datum['yifu'] = $transaModel->getOrderStatusIdDateYsModel($datum['id'], $datum['create_date'], $datum['order_company_id'], $datum['certificate_code'], 1, 2)['all_price'];
                $datum['receivable'] = $result['sale_price'] ?: '';
            }

            $businData = $businessModel->getCerFieldDataModel($datum['certificate_code']);
            if (!empty($businData)) {

                $result = $businData;

                $datum['person_name'] = '';
                if (isset($result['enterprise_name'])) {
                    $datum['enterprise_name'] = $result['enterprise_name'];
                } else {
                    $datum['enterprise_name'] = '';
                }
                $datum['typess'] = 2;
                $datum['employ_unit_title'] = '';
                $datum['sale_org'] = '';
                $datum['yingfu'] = $result['cost_price'];
                $datum['yishou'] = $transaModel->getOrderStatusIdDateYsModel($datum['id'], $datum['create_date'], $datum['order_company_id'], $datum['certificate_code'], 1, 1)['all_price'];
                $datum['yifu'] = $transaModel->getOrderStatusIdDateYsModel($datum['id'], $datum['create_date'], $datum['order_company_id'], $datum['certificate_code'], 1, 2)['all_price'];
                $datum['reg_unit'] = '';
                $datum['receivable'] = $result['sale_price'] ?: '';
            }

            $comData = $companyModel->getCertificateCodeFindModel($datum['certificate_code']);
            if (!empty($comData)) {

                $result = $comData;

                $datum['typess'] = 2;
                $datum['person_name'] = $result['person_name'];
                $datum['enterprise_name'] = '';
                if (isset($result['certificate_id'][3])) {
                    $cid = $result['certificate_id'][3];
                } else {
                    $cid = 0;
                }
                //查询订单属于续签还是已售出
                if ($orderDealMode->getCerComIdFindModel($datum['order_company_id'], $datum['certificate_code']) === '续签') {
                    $datum['yingfu'] = $result['contract_price'];
                } else {
                    $datum['yingfu'] = $personModel->getPersonIdCardCerOrderModel($result['person_id_card'], $cid)['person_price'] ?: 0;
                }
                $datum['yishou'] = $transaModel->getOrderStatusIdDateYsModel($datum['id'], $datum['create_date'], $datum['order_company_id'], $datum['certificate_code'], 1, 1)['all_price'];
//                $datum['yishou'] = $personModel->getPersonIdCardOrderModel($result['person_id_card'])['person_price']?:0;
                $datum['yifu'] = $transaModel->getOrderStatusIdDateYsModel($datum['id'], $datum['create_date'], $datum['order_company_id'], $datum['certificate_code'], 1, 2)['all_price'];
                $datum['employ_unit_title'] = $result['employ_unit_title'];

                $datum['sale_org'] = $result['sale_org']['text'];
                $datum['reg_unit'] = $result['reg_unit'];
//                if ($result['people_num'] <1){
//                    $result['people_num'] = 1;
//                }
                $datum['receivable'] = $result['price_unit'] ?: '';
            }

            $exData = $exchangeModel->getFinanceFieldFindModel($datum['certificate_code']);
            if (!empty($exData)) {

                $result = $exData;

                $datum['typess'] = 2;
                $datum['person_name'] = $result['person_name'];
                $datum['enterprise_name'] = isset($result['enterprise_name']) ?: '';
                $datum['yingfu'] = $result['get_price'] ?: '';
                $datum['yishou'] = $transaModel->getOrderStatusIdDateYsModel($datum['id'], $datum['create_date'], $datum['order_company_id'], $datum['certificate_code'], 1, 1)['all_price'];
                $datum['yifu'] = $transaModel->getOrderStatusIdDateYsModel($datum['id'], $datum['create_date'], $datum['order_company_id'], $datum['certificate_code'], 1, 2)['all_price'];
                $datum['employ_unit_title'] = '';

                $datum['sale_org'] = '';
                $datum['reg_unit'] = $result['unit_reg_title'];
                $datum['receivable'] = $result['out_price'] ?: '';
            }

            //收付款编号是否对应多条收付款
            $multiple = $transaModel->getTransactionCodeIsDtDataModel($datum['transaction_code']);
            if ($multiple > 1) {
                $datum['is_multiple'] = 1;//存在多条
            } else {
                $datum['is_multiple'] = 0;//不存在多条
            }

            //如果未设置typess  $typess = 0
            if (!isset($datum['typess'])) {
                $datum['typess'] = 0;
            }
        }

        return $data;
    }

    public function getEnterOrderCountNum($data, $uid)
    {
        if (!is_array($data)) {
            $data = $data->toArray();
        }
        foreach ($data as &$datum) {

            //查询企业证书注册订单个数
            $enter_count = Db::table('order_enterprise_company')
                ->alias('c')
                ->join('order_enterprise_certificate_register r', 'r.certificate_code = c.certificate_code')
                ->where(['r.reg_unit' => $datum['enterprise_name'], 'c.status' => 1])
                ->whereNull('r.delete_date')
                ->count();

            //企业倒证
            $enter_count += Db::table('order_enterprise_exchange')->where(['unit_reg_title' => $datum['enterprise_name'], 'status' => 1])->count();
            //企业证书
            $enter_count += Db::table('order_enterprise_certificate_business')->whereNull('delete_date')->where(['enterprise_name' => $datum['enterprise_name'], 'status' => 1])->count();

            //查询个人提交的企业证书注册订单个数
            $people_enter_count = Db::table('order_enterprise_company')
                ->alias('c')
                ->join('order_enterprise_certificate_register r', 'r.certificate_code = c.certificate_code')
                ->where(['r.reg_unit' => $datum['enterprise_name'], 'c.status' => 1, 'c.get_uid' => $uid])
                ->whereNull('r.delete_date')
                ->count();

            //企业倒证
            $people_enter_count += Db::table('order_enterprise_exchange')->where(['unit_reg_title' => $datum['enterprise_name'], 'status' => 1, 'get_uid' => $uid])->count();
            //企业证书
            $people_enter_count += Db::table('order_enterprise_certificate_business')->whereNull('delete_date')->where(['enterprise_name' => $datum['enterprise_name'], 'status' => 1, 'get_uid' => $uid])->count();

            $datum['order_goods_number'] = $enter_count . '/' . $people_enter_count;

            //临时用来改变合作状态
            if ($enter_count > 0) {
                $datum['status'] = [
                    'id' => 2,
                    'text' => stateData::$_enter_status[2]
                ];
            }
        }

        return $data;
    }

    /**
     * 删除订单为0的内容
     * @param $data
     * @return mixed
     */
    public function delOrderEmpty($data)
    {
        if (!is_array($data)) {
            $data = $data->toArray();
        }

        foreach ($data as $i => $iValue) {
            if (isset($iValue['person_id_card']) && empty($iValue['person_id_card'])){
                unset($data[$i]);
                continue;
            }
            if (isset($iValue['order_goods_number'])) {
                $number = explode('/', $iValue['order_goods_number'])[1];
                $number2 = explode('/', $iValue['order_goods_number'])[0];
                if ($number == 0 && $number2 == 0) {
                    unset($data[$i]);
                }
            } else {
                unset($data[$i]);
            }
        }

        return array_values($data);
    }

    //统计客户管理出证单位订单信息
    public function getCzdwOrderNum($data, $uid)
    {
        $exchange = new OrderEnterpriseExchange();
        $company = new OrderEnterpriseCompany();
        $reg = new OrderEnterpriseCertificateRegister();

        $totalDdl = 0;
        $myDdl = 0;
        foreach ($data as $k => &$datum) {

            if ($datum['type'] == 1) {//查询出证单位订单量
                $totalDdl = $exchange->getChuZhengUnitOrderNumModel($datum['title']);
                $myDdl = $exchange->getUidChuZhengUnitOrderNumModel($datum['title'], $uid);
                $datum['order_goods_number'] = $myDdl . '/' . $totalDdl;
            } elseif ($datum['type'] == 2) {//查询聘用单位订单量
                $totalDdl = $company->getPinYongUnitOrderNumModel($datum['title']);
                $myDdl = $company->getUidPinYongUnitOrderNumModel($datum['title'], $uid);
                $totalDdl += $exchange->getPinYongUnitOrderNumModel($datum['title']);
                $myDdl += $exchange->getUidPinYongUnitOrderNumModel($datum['title'], $uid);

                $datum['order_goods_number'] = $myDdl . '/' . $totalDdl;
            } else {//查询注册单位订单量
                $totalDdl = $exchange->getRegUnitOrderNumModel($datum['title']);
                $myDdl = $exchange->getUidRegUnitOrderNumModel($datum['title'], $uid);

                //查询企业证书注册订单量
                $regData = $reg->getRegUnitCerModel($datum['title']);
                foreach ($regData as $regDatum) {
                    $totalDdl += $company->getCerOrderNumModel($regDatum);
                    $myDdl += $company->getUidCerOrderNumModel($regDatum, $uid);

                    $totalDdl += $reg->getCerOrderNumModel($regDatum);
                    $myDdl += $reg->getUidCerOrderNumModel($regDatum, $uid);

                    $totalDdl += $exchange->getRegUnitOrderNumModel($regDatum);
                    $myDdl += $exchange->getUidRegUnitOrderNumModel($regDatum, $uid);

                }
                $datum['order_goods_number'] = $myDdl . '/' . $totalDdl;
            }
        }
        return $data;
    }

//    public function getFromFieldEmpty($data)
//    {
//        foreach ($data as $k => $datum) {
//            if (empty($datum[$k]) && $datum[$k] !=0){
//                return false;
//            }
//        }
//        return true;
//    }

    /**
     *  查询订单是否有退单|注销
     * op 0 没状态 1退单 2注销
     * @param $data
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderIsOp($data)
    {
        foreach ($data as &$item) {
            $ops = Db::table('order_deal_chargeback')->where('certificate_code="' . $item['certificate_code'] . '" and order_company_id=' . $item['id'])->whereNull('delete_date')->order('create_date DESC')->find();
//            if (!empty($op) && empty($op['delete_date']) && $op['is_complete'] == 0){
            if (!empty($ops) && empty($ops['delete_date'])) {

                if ($ops['type'] == 1) {
                    $op = 1;
                } else {
                    $op = 2;
                }
            } else {
                $op = 0;
            }
            $item['op'] = $op;
            if (isset($ops['notifier_get_uid'])) {
                $item['op_uid'] = $ops['notifier_get_uid'] ?: '';
            } else {
                $item['op_uid'] = '';
            }
            if (isset($item['reason'])) {
                if (empty($item['reason'])) {
                    $item['reason'] = '';
                }
            } else {
                $item['reason'] = '';
            }
        }
        return $data;
    }

    /**
     * 获取证书办理主订单id status certificate_code
     */
    public function getMianOrderInfo($data)
    {
        $OrderPersonCertificateRegisterModel = new OrderPersonCertificateRegister();
        $OrderEnterpriseCompanyModel = new OrderEnterpriseCompany();
        //所有主订单信息
        $personData = $OrderPersonCertificateRegisterModel->getDataModel();

        foreach ($data as $key => &$datum) {
            $ops = Db::table('order_deal_chargeback')->where('certificate_code="' . $datum['certificate_code'] . '" and order_company_id=' . $datum['id'])->whereNull('delete_date')->order('create_date DESC')->find();
//            if (!empty($op) && empty($op['delete_date']) && $op['is_complete'] == 0){
            if (!empty($ops)) {
                if ($ops['type'] == 1) {
                    $op = 1;
                } else {
                    $op = 2;
                }
            } else {
                $op = 0;
            }
            $datum['op'] = $op;
            if (isset($ops['notifier_get_uid'])) {
                $datum['op_uid'] = $ops['notifier_get_uid'] ?: '';
            } else {
                $datum['op_uid'] = '';
            }
            if (isset($datum['reason'])) {
                if (empty($datum['reason'])) {
                    $datum['reason'] = '';
                }
            } else {
                $datum['reason'] = '';
            }

//            $datum = $datum->toArray();
            $datum['main_id'] = '';
            $datum['main_status'] = '';
            $datum['main_certificate_code'] = '';

            foreach ($personData as $personDatum) {

                $arr = explode(',', $personDatum['ancillary_businesses_id']);
//                print_r ($datum['id']);
//                echo PHP_EOL;
//                print_r ($arr);
//                echo  PHP_EOL;
                if (in_array($datum['id'], $arr)) {

                    //如果已经售卖 通过身份证号码查询售卖信息
                    if (!empty($personDatum['status']['id'])) {

                        if ($personDatum['status']['id'] == 3) {
                            $companyData = $OrderEnterpriseCompanyModel->getPersonIdCardFindModel($personDatum['person_id_card']);

                            if ($companyData) {
                                $datum['main_id'] = $companyData[0]['id'];
                                $datum['main_status'] = $personDatum['status']['id'];
                                $datum['main_certificate_code'] = $companyData[0]['certificate_code'];
                            }
                        } else {

                            $companyData = $OrderPersonCertificateRegisterModel->getIdDetails($personDatum['id']);

                            if ($companyData) {
                                $datum['main_id'] = $companyData['id'];
                                $datum['main_status'] = $companyData['status']['id'] ?: 0;
                                $datum['main_certificate_code'] = $companyData['certificate_code'];
                            }
                        }
                    } else {
                        $companyData = $OrderPersonCertificateRegisterModel->getIdDetails($personDatum['id']);
                        if ($companyData) {
                            $datum['main_id'] = $companyData['id'];
                            $datum['main_status'] = $companyData['status']['id'] ?: 0;
                            $datum['main_certificate_code'] = $companyData['certificate_code'];
                        }
                    }
                }
                unset($companyData);
            }
        }
        return $data;
    }


    /**
     * 查询表单是否有定时提醒内容
     * 判断第二步是否存在空值
     */

    public function whDingshiqi($data, $type = '')
    {
        if (empty($data)) {
            return [];
        }
        //企业证书
        $qyzs = [
            'sale_price',
            'cost_price',
            'sh_uid'
        ];
        //倒证
        $dz = [
            'out_unit',
            'out_name',
            'out_mobile',
            'certificate_b',
            'social_security',
            'cycle',
            'project',
            'transfer',
            'get_org',
            'get_uid',
            'get_price',
            'person_name',
            'id_card',
            'reg_file',
//            'info_file',
//            'other_file',
//            'b_reg_electronic_certificate_date'
        ];
        if (!is_one_dimensional_array($data)) {
            foreach ($data as &$datum) {
                $dingshiqi = Db::table('user_message')->where(['b_id' => $datum['certificate_code'], 'is_executed' => 2, 'type' => 7, 'order_company_id' => $datum['id']])->value('id');
                if ($dingshiqi) {
                    $datum['dingshiqi'] = 1;
                } else {
                    $datum['dingshiqi'] = 0;
                }

                if ($type == 'qyzs') {
                    foreach ($qyzs as $qyzItem) {
                        if (array_key_exists($qyzItem, $datum)) {
                            if ($qyzItem == 'sh_uid') {
                                if (empty($datum[$qyzItem]['id'])) {
                                    $datum['is_sup_empty'] = true;
                                    continue;
                                }
                            } else {
                                if (!$datum[$qyzItem]) {
                                    $datum['is_sup_empty'] = true;
                                    continue;
                                }
                            }

                            $datum['is_sup_empty'] = false;
                        }
                    }
                }

                if ($type == 'dz') {
                    foreach ($dz as $qyzItem) {
                        if (array_key_exists($qyzItem, $datum)) {
                            if (!$datum[$qyzItem]) {
                                $datum['is_sup_empty'] = true;
                                continue;
                            }
                            $datum['is_sup_empty'] = false;
                        }
                    }
                }
            }
        } else {
            $dingshiqi = Db::table('user_message')->where(['b_id' => $data['certificate_code'], 'is_executed' => 2, 'type' => 7, 'order_company_id' => $data['id']])->value('id');
            if ($dingshiqi) {
                $data['dingshiqi'] = 1;
            } else {
                $data['dingshiqi'] = 0;
            }

            if ($type == 'qyzs') {
                foreach ($qyzs as $qyzItem) {
                    if (array_key_exists($qyzItem, $data)) {
                        if ($qyzItem == 'sh_uid') {
                            if (empty($data[$qyzItem]['id'])) {
                                $data['is_sup_empty'] = true;
                                continue;
                            }
                        } else {
                            if (!$data[$qyzItem]) {
                                $data['is_sup_empty'] = true;
                                continue;
                            }
                        }
                        $data['is_sup_empty'] = false;
                    }
                }
            }

            if ($type == 'dz') {
                foreach ($dz as $qyzItem) {
                    if (array_key_exists($qyzItem, $data)) {
                        if (!$data[$qyzItem]) {
                            $data['is_sup_empty'] = true;
                            continue;
                        }
                        $data['is_sup_empty'] = false;
                    }
                }
            }
        }
        return $data;
    }


    /**
     * 查询该审核订单是否有审核权限
     */
    public function isSh($data, $uid)
    {
        if (empty($data)) {
            return [];
        }
        if (is_one_dimensional_array($data)) {
            if ($data['responsibility_uid'] && $data['status']['id'] == 0) {//第一步待审核
                if ($data['responsibility_uid'] == $uid) {
                    $data['is_sh'] = 1;
                } else {
                    $data['is_sh'] = 0;
                }
            } else if ($data['certificate_characteristic_reviewed_uid']['id'] && $data['certificate_characteristic_status']['id'] == 2) {
                if ($data['certificate_characteristic_reviewed_uid']['id'] == $uid) {
                    $data['is_sh'] = 1;

                } else {
                    $data['is_sh'] = 0;
                }
            } else {
                $data['is_sh'] = 0;
            }

            if ($data['certificate_characteristic_status']['id'] != 1) {
                $data['certificate_characteristic'] = [
                    'id' => 0,
                    'text' => ''
                ];
            }

            return $data;
        }

        foreach ($data as &$datum) {
            if (empty($datum)) {
                continue;
            }
            if ($datum['responsibility_uid'] && $datum['status']['id'] == 0) {//第一步待审核
                if ($datum['responsibility_uid'] == $uid) {
                    $datum['is_sh'] = 1;
                } else {
                    $datum['is_sh'] = 0;
                }
            } else if ($datum['certificate_characteristic_reviewed_uid']['id'] && $datum['certificate_characteristic_status']['id'] == 2) {
                if ($datum['certificate_characteristic_reviewed_uid']['id'] == $uid) {
                    $datum['is_sh'] = 1;

                } else {
                    $datum['is_sh'] = 0;
                }
            } else {
                $datum['is_sh'] = 0;
            }

            if ($datum['certificate_characteristic_status']['id'] != 1) {
                $datum['certificate_characteristic'] = [
                    'id' => 0,
                    'text' => ''
                ];
            }
        }
        return $data;
    }


    /**
     * 判断证书关联人才是新出还是续出
     */
    public function getOrderStatus($id, $cer)
    {
        $orderEnterCompanyModel = new OrderEnterpriseCompany();

        //查询ID证书编号对应的人才身份证号码
        $idcard = $orderEnterCompanyModel->getOrderPersonIdCardModel($id);

        //查询该id是否已经成交过
        $perData = $orderEnterCompanyModel->getPersonIdCardNewOrderModel($idcard);
        //成交次数大于1
        if (count($perData) > 1) {
            return 3; //已经成交过续出
        }
        return 1; //未成交过 新出
    }


    /**
     * 通过 “订单编码+销售时间” 补充完整订单信息
     */
    public function suppOrderDzInfo($orderId, $uid)
    {
        $chargebackModel = new OrderDealChargeback();
        $exchangeModel = new OrderEnterpriseExchange();
        $publicity = new Publicity();

        //查询基础数据
        $result = $exchangeModel->getExchangeListModel('', '', $orderId);

        //查询该订单是否有退单
        foreach ($result as $value) {
            $chargebackData = $chargebackModel->getOrderIdCerIsChargeBackModel($value['id'], $value['certificate_code']);
            if (!empty($chargebackData)) {

                $value['performance'] = $chargebackData['performance'];

                $value['create_date'] = $chargebackData['create_date'];
                $value['sale_date'] = $chargebackData['create_date'];
                $value['tuidan'] = true;
                $value['reason'] = $chargebackData['reason'];
                $value['status'] = [
                    'id' => 999,
                    'text' => '退单完成'
                ];
                $result[] = $value;
            }
        }

        //获取公式资料
        return $publicity->getPublicyInfo($result, $uid);
    }


    public function suppOrderGszsInfo($orderId)
    {
        $deal = new OrderDeal();
        $chargebackModel = new OrderDealChargeback();
        //第二步填写字段
        $zszccj = [
            'employ_unit_title',
            'employ_unit_name',
            'employ_unit_mobile'
        ];
        $result = (new OrderEnterpriseCompany())->getCerIdFindSelectModel($orderId['id'], $orderId['certificate_code']);

        //查询该订单是否有退单
        foreach ($result as $values) {
            $chargebackData = $chargebackModel->getOrderIdCerIsChargeBackModel($values['id'], $values['certificate_code']);
            if (!empty($chargebackData)) {

                $values['performance'] = $chargebackData['performance'];

                $values['create_date'] = $chargebackData['create_date'];
                $values['sale_date'] = $chargebackData['create_date'];
                $values['tuidan'] = true;
                $values['reason'] = $chargebackData['reason'];
                $values['status'] = [
                    'id' => 999,
                    'text' => '退单完成'
                ];
                $result[] = $values;
            }
        }

        //使用模型转换器转换
        foreach ($result as &$value) {
            //获取补充资料
            $gszl = $deal->getGszlDataModel($value['id'], $value['certificate_code']);

            //待优化
            if (!empty($gszl)) {
                $value['electronic_certificate_file'] = $gszl['electronic_certificate_file'] ?: '';
                $value['electronic_certificate_file_illustrate_name'] = $gszl['electronic_certificate_file_illustrate_name'] ?: '';
                $value['electronic_certificate_file_illustrate'] = $gszl['electronic_certificate_file_illustrate'] ?: '';
                $value['electronic_certificate_date'] = $gszl['electronic_certificate_date'] ?: '';
                $value['b_electronic_certificate_file_illustrate'] = $gszl['b_electronic_certificate_file_illustrate'] ?: '';
                $value['b_electronic_certificate_file_name'] = $gszl['b_electronic_certificate_file_name'] ?: '';
                $value['b_electronic_certificate_file'] = $gszl['b_electronic_certificate_file'] ?: '';
                $value['b_electronic_certificate_date'] = $gszl['b_electronic_certificate_date'] ?: '';
                $value['b_reg_electronic_certificate_date'] = $gszl['b_reg_electronic_certificate_date'] ?: '';
                $value['order_status'] = $gszl['status'];

            } else {
                $value['electronic_certificate_file'] = '';
                $value['electronic_certificate_file_illustrate'] = '';
                $value['electronic_certificate_file_illustrate_name'] = '';
                $value['electronic_certificate_date'] = '';
                $value['b_electronic_certificate_file_illustrate'] = '';
                $value['b_electronic_certificate_file_name'] = '';
                $value['b_electronic_certificate_file'] = '';
                $value['b_electronic_certificate_date'] = '';
                $value['b_reg_electronic_certificate_date'] = '';
                $value['order_status'] = '';
            }

            //表单定时器
//            $dingshiqi = Db::table('user_message')->where([
//                'b_id' => $value['certificate_code'],
//                'is_executed' => 2,
//                'type' => 7,
//                'order_company_id' => $value['id']
//            ])->find();
//
//            if ($dingshiqi) {
//                $value['dingshiqi'] = 1;
//            } else {
//                $value['dingshiqi'] = 0;
//            }

            if ($value['certificate_leixing']) {
                $value['certificate_leixing'] = [
                    'id' => $value['certificate_id'][0],
                    'text' => $value['certificate_leixing']
                ];
            } else {
                $value['certificate_leixing'] = [
                    'id' => '',
                    'text' => $value['certificate_leixing']
                ];
            }
            if ($value['certificate_leibie']) {
                $value['certificate_leibie'] = [
                    'id' => $value['certificate_id'][1],
                    'text' => $value['certificate_leibie']
                ];
            } else {
                $value['certificate_leibie'] = [
                    'id' => '',
                    'text' => $value['certificate_leibie']
                ];
            }

            if ($value['certificate_dengji']) {
                $value['certificate_dengji'] = [
                    'id' => $value['certificate_id'][2],
                    'text' => $value['certificate_dengji']
                ];
            } else {
                $value['certificate_dengji'] = [
                    'id' => '',
                    'text' => $value['certificate_dengji']
                ];
            }

            if ($value['certificate_zhuanye']) {
                $value['certificate_zhuanye'] = [
                    'id' => $value['certificate_id'][3],
                    'text' => $value['certificate_zhuanye']
                ];
            } else {
                $value['certificate_zhuanye'] = [
                    'id' => '',
                    'text' => $value['certificate_zhuanye']
                ];
            }


//            //判断第二步是否存在空值
//            foreach ($zszccj as $qyzItem) {
//                if (array_key_exists($qyzItem, $value)) {
//                    if (!$value[$qyzItem]) {
//                        $value['is_sup_empty'] = true;
//                        continue;
//                    }
//                    $value['is_sup_empty'] = false;
//                }
//            }
        }
        return $result;
    }

    /**
     * 倒证详情点击生成信息生成
     * @param $id
     * @param $certificate_code
     * @return void
     * @throws \Exception
     */
    public function clickInfoGenerate($id, $certificate_code)
    {
        try {
            $redis = new RedisService();
            $orderEnterExchangeModel = new OrderEnterpriseExchange();
            $orderEnterExchangeInfo = $orderEnterExchangeModel->getIdCerFindModel($id, $certificate_code);
            //初始化信息生成状态  1-未生成
            $info_generate_status = $orderEnterExchangeModel::INFO_GENERATE_STATUS_ONE;
            //操作状态 1-已操作 0-未操作
            $info_generate_operate = 1;
            //判断倒证信息是否存在
            if (!$orderEnterExchangeInfo) {
                throw new Exception('倒证信息不存在');
            }
            //判断信息生成的联系电话是否存在
            if ($orderEnterExchangeInfo && !$orderEnterExchangeInfo['info_generate_mobile']) {
                throw new Exception('信息生成需要的联系电话不存在！');
            }
            //判断该倒证信息中的身份证号是否在人才库中存在
            $cluePersonModel = new CluePerson();
            $idCardExist = $cluePersonModel->getPersonIdCard($orderEnterExchangeInfo['id_card']);
            if ($idCardExist) {
                //将信息生成状态改为3 信息存在状态 将操作状态改为已操作
                $info_generate_status = $orderEnterExchangeModel::INFO_GENERATE_STATUS_THREE;
                $orderEnterExchangeModel->editInfoGenerateStatus($id, $info_generate_status, $info_generate_operate);
                //更新缓存
                $redis->delOrderDzData($orderEnterExchangeInfo,'order_dz');
                throw new Exception('该人才已存在');
            }
            //判断人才电话表中是否存在该手机号
            $clueMobileModel = new ClueMobile();
            $mobileExist = $clueMobileModel->getMobileInfoByMobile($orderEnterExchangeInfo['info_generate_mobile']);
            if ($mobileExist) {
                //将信息生成状态改为3 信息存在状态
                $info_generate_status = $orderEnterExchangeModel::INFO_GENERATE_STATUS_THREE;
                $orderEnterExchangeModel->editInfoGenerateStatus($id, $info_generate_status, $info_generate_operate);
                //更新缓存
                $redis->delOrderDzData($orderEnterExchangeInfo,'order_dz');
                throw new Exception('该联系电话已存在');
            }
            //人才库生成一条信息将姓名 身份证号 证书类型-类别-等级-专业 证书到期时间、B证 B证到期时间 并将联系电话同步到clueMobile表中
            $cluePersonData = [];
            $cluePersonData['person_name'] = $orderEnterExchangeInfo['person_name'] ?? '';
            $cluePersonData['person_id_card'] = $orderEnterExchangeInfo['id_card'] ?? '';
            $cluePersonData['certificate_id'] = $orderEnterExchangeInfo['certificate_id'] ?? '';
            $cluePersonData['create_time'] = date('Y-m-d H:i:s');
            $cluePersonData = $this->handleCertificateInfo($orderEnterExchangeInfo, $cluePersonData);
            //获取order_deal表中的证书到期时间和b证到期时间
            $orderDealModel = new OrderDeal();
            $orderDealInfo = $orderDealModel->getCertDateOrB($certificate_code);
            if ($orderDealInfo) {
                if ($orderDealInfo['electronic_certificate_date']) {
                    $cluePersonData['certificate_period_of_validity'] = $orderDealInfo['electronic_certificate_date'];
                }
                if ($orderDealInfo['electronic_certificate_date']) {
                    $cluePersonData['certificate_b_period_of_validity'] = $orderDealInfo['b_reg_electronic_certificate_date'];
                }
            }
            $clueMobileData = [
                'clue_p_id' => 0,
                'mobile' => $orderEnterExchangeInfo['info_generate_mobile'],
                'create_date' => date('Y-m-d H:i:s'),
                'type' => 1
            ];
            Db::transaction(function () use (
                $redis,
                $orderEnterExchangeInfo,
                $cluePersonData,
                $clueMobileData,
                $cluePersonModel,
                $clueMobileModel,
                $orderEnterExchangeModel,
                $id,
                $info_generate_operate
            ) {
                if ($cluePersonData) {
                    //人才库添加信息
                    $cluePersonModel->save($cluePersonData);
                    $clueMobileData['clue_p_id'] = $clueMobileModel->getLastInsID();
                    //人才联系方式入库
                    $clueMobileModel->save($clueMobileData);
                    //倒证订单 信息生成状态改为 2-信息生成 操作状态改为已操作
                    $info_generate_status = $orderEnterExchangeModel::INFO_GENERATE_STATUS_TWO;
                    $orderEnterExchangeModel->editInfoGenerateStatus($id, $info_generate_status, $info_generate_operate);
                    $redis->delOrderDzData($orderEnterExchangeInfo,'order_dz');
                }
            });

        } catch (\Exception $exception) {
            // 存在程序运行错误，则记录错误信息
            if (error_get_last()) {
                Log::error(json_encode(error_get_last()));
            }
            Log::error(
                $exception->getFile() . '第' . $exception->getLine() . '行发生错误：' . $exception->getMessage()
            );
            throw new \Exception($exception->getMessage());
        }
    }


    public function handleCertificateInfo($info, $data = [])
    {
        if (!$info) return [];
        $array = ['certificate_leixing', 'certificate_leibie', 'certificate_dengji', 'certificate_zhuanye', 'certificate_b'];
        foreach ($array as $item) {
            if (!isset($info[$item])) continue;
            if ($info[$item]) {
                if (is_array($info[$item]) && $info[$item] && isset($info[$item]['id'])) {
                    $data[$item] = $info[$item]['id'];
                } elseif (!is_array($info[$item])) {
                    $data[$item] = $info[$item];
                }
            }
        }
        return $data;
    }

    /**
     * 倒证详情点击注册完成
     * @param $id
     * @return void
     * @throws \Exception
     */
    public function registerOver($id)
    {
        try {
            $orderEnterExchangeModel = new OrderEnterpriseExchange();
            $info = $orderEnterExchangeModel->getWhereIdData($id);
            if(!$info){
                throw new Exception("信息不存在！");
            }
            if($info['status']['id'] != 1){
                throw  new Exception("状态不正确不可操作！");
            }
            $redis = new RedisService();
            //更新缓存
            $redis->delOrderDzData($info,'order_dz');
            $orderEnterExchangeModel->certificateRegModel($id);
        } catch (\Exception $exception) {
            // 存在程序运行错误，则记录错误信息
            if (error_get_last()) {
                Log::error(json_encode(error_get_last()));
            }
            Log::error(
                $exception->getFile() . '第' . $exception->getLine() . '行发生错误：' . $exception->getMessage()
            );
            throw new \Exception($exception->getMessage());
        }
    }


}